from os import path

from PyPDF2 import PdfFileReader, PdfFileWriter

from utils import catalog_util


class PdfHandler:
    """ 处理单本pdf"""

    def __init__(self, pdf_path, out_dir):
        self.pdf_path = pdf_path
        self.out_dir = out_dir

    def remove_page(self, page_num):
        pdf_writer = PdfFileWriter()
        with open(self.pdf_path, 'rb') as f:
            # 文件名字
            name = path.basename(f.name)
            pdf_reader = PdfFileReader(f)
            # 删除第一页后，保存到目标目录
            num_pages = pdf_reader.getNumPages()
            for page in range(0, num_pages):
                if page != page_num:
                    page_obj = pdf_reader.getPage(page)
                    pdf_writer.addPage(page_obj)

            # 写入一个测试的页签
            # 使用方法： addBookmark(书签文字, 书签页码, 书签的父目录)，返回值是书签（可以作为其他
            # pdf_writer.addBookmark("我是hi测试", 100, parent=None)
            # skip, catalog = self.read_catalog()
            # self.add_catalog(pdf_writer, catalog, skip, None)
            # 生成新的文件
            with open(self.out_dir + "/" + name, 'wb') as of:
                pdf_writer.write(of)
            print("生成新pdf成功")

    def add_catalog(self, pdf_writer: PdfFileWriter, catalog, skip, parent=None):
        for cata in catalog:
            real_page = cata.get('page') + skip
            pp = pdf_writer.addBookmark(cata.get('title'), real_page, parent)
            if cata.get('children'):
                self.add_catalog(pdf_writer, cata.get('children'), skip, pp)

    def read_catalog(self):
        catalog_txt = self.pdf_path.replace(".pdf", ".txt")
        with open(catalog_txt, 'r', encoding="utf-8") as f:
            lines = [line.rstrip("\n").rstrip(" ") for line in f.readlines()]
            skip = int(lines[0].strip())
            # utils = CatalogUtil()
            return skip, catalog_util.build_tree(lines[1:])

    def bookmark_listhandler(self, pdf_reader, list):
        for message in list:
            if isinstance(message, dict):
                print(message['/Title'], pdf_reader.getDestinationPageNumber(message) + 1)
            else:
                self.bookmark_listhandler(pdf_reader, message)

    def read_outline(self):
        """ 读取pdf"""
        with open(self.pdf_path, 'rb') as f:
            # 文件名字
            pdf_reader = PdfFileReader(f)
            outline = pdf_reader.getOutlines()
            self.bookmark_listhandler(pdf_reader, outline)
